import React, { memo, useEffect, useState } from "react";
import type { FC, ReactNode } from "react";
import { DiscoverPageWrapper } from "./style";
import { useLocation, useParams } from "react-router-dom";
import { feachHighqualityAction, feachRankingAction, feachTopplayListAction, feachrcmdSongMenuAction, replaceTopPlayListAction } from "./store";
import { useAppDispatch, useAppSelector } from "@/store";
import DisMenulist from "./cpns/dis-menulist";
import { shallowEqual } from "react-redux";

interface IProps {
  children?: ReactNode;
}

const DiscoverPage: FC<IProps> = () => {
  const params = useParams()
  const location = useLocation()
  const { discText } = params
  const { index } = location?.state

  const limit = 50
  const [offset, setOffset] = useState(0)
  const [currSize, setCurrSize] = useState(1)
  const [before, setBefore] = useState(0)
  const dispatch = useAppDispatch()

  useEffect(() => {
    if (discText && index === 1) {
      dispatch(feachrcmdSongMenuAction())
    } else if (discText && index === 2) {
      dispatch(feachHighqualityAction({ before }))
    } else if (discText && index === 4) {
      dispatch(feachRankingAction())
    } else {
      if (offset === 0) {
        dispatch(replaceTopPlayListAction([]))
      }
      if (discText) dispatch(feachTopplayListAction({ cat: discText, offset, limit }))
    }
  }, [dispatch, discText, limit, offset, index, before])

  const { topPlatList, results, highqualist, lasttime, rankings } = useAppSelector((state) => ({
    topPlatList: state.discoverPage.topPlatList,
    results: state.discoverPage.results,
    highqualist: state.discoverPage.highqualist,
    lasttime: state.discoverPage.lasttime,
    rankings: state.discoverPage.rankings
  }), shallowEqual)

  const onUploadFn = () => {
    if (index === 2) {
      setBefore(lasttime)
    } else {
      let newOffset = offset
      let newCurrSize = currSize
      setCurrSize(newCurrSize + 1)
      newOffset = newCurrSize * limit
      setOffset(newOffset)
    }
  }

  return <DiscoverPageWrapper>
    {topPlatList && index !== 1 && index !== 2 && index !== 4 && <DisMenulist menuList={topPlatList} onUploadFn={onUploadFn} />}
    {results && index === 1 && <DisMenulist menuList={results} isButtom={false} />}
    {highqualist && index === 2 && <DisMenulist menuList={highqualist} onUploadFn={onUploadFn} />}
    {rankings && index === 4 && <DisMenulist menuList={rankings} isButtom={false} />}
  </DiscoverPageWrapper>;
};

export default memo(DiscoverPage);